import "package:mobx/mobx.dart";
import "package:hinge/common/models/topic_model.dart";
import "package:hinge/common/models/topic_comment_model.dart";
import "package:hinge/common/models/user_model.dart";
import "package:hinge/common/services/topic_service.dart";
import "package:hinge/common/services/topic_comment_service.dart";
import "package:hinge/common/services/user_service.dart";
import "package:go_router/go_router.dart";
import "package:flutter/material.dart";
import "package:hinge/store/root_store.dart";

part "topic_store.g.dart";

class TopicStore = _TopicStore with _$TopicStore;

abstract class _TopicStore with Store {
  // 根Store引用 - 使用延迟获取避免循环引用
  RootStore get _rootStore => RootStore();

  @observable
  bool isLoading = false;

  @observable
  TopicModel? topic;

  @observable
  ObservableList<TopicCommentModel> comments =
      ObservableList<TopicCommentModel>.of([]);

  @observable
  String commentText = '';

  @observable
  bool isUserLoggedIn = false;

  @observable
  UserModel? currentUser;

  @computed
  bool get hasComments => comments.isNotEmpty;

  @computed
  bool get canComment => isUserLoggedIn && currentUser != null;

  @action
  void setCommentText(String value) {
    commentText = value;
  }

  @action
  Future<void> checkLoginStatus() async {
    // 获取之前的登录状态，用于比较是否发生了变化
    final prevLoggedIn = isUserLoggedIn;
    final prevUserId = currentUser?.id;

    // 这里应该是实际检查用户登录状态的逻辑
    final loggedInUser = UserService.getCurrentUser();

    if (loggedInUser != null && !UserService.isGuestUser()) {
      isUserLoggedIn = true;
      currentUser = loggedInUser;
    } else {
      isUserLoggedIn = false;
      currentUser = loggedInUser; // 可能是游客或null
    }

    // 如果登录状态发生变化，打印日志
    if (prevLoggedIn != isUserLoggedIn || prevUserId != currentUser?.id) {
      print(
        'TopicPage 登录状态发生变化: ${isUserLoggedIn ? '已登录' : '未登录'}, 用户ID: ${currentUser?.id}',
      );
    }
  }

  @action
  Future<void> loadTopicData(int topicId) async {
    isLoading = true;

    try {
      // 检查用户登录状态
      await checkLoginStatus();

      // 获取话题
      final topicData = TopicService.getTopicById(topicId);
      if (topicData == null) {
        print('话题不存在: $topicId');
        isLoading = false;
        return;
      }

      // 获取评论
      final commentsList = TopicCommentService.getCommentsByTopicId(topicId);

      // 按时间排序评论 (新的在前)
      commentsList.sort((a, b) => b.timestamp.compareTo(a.timestamp));

      // 更新状态
      topic = topicData;
      comments.clear();
      comments.addAll(commentsList);
    } catch (e) {
      print('加载话题数据出错: $e');
    } finally {
      isLoading = false;
    }
  }

  @action
  Future<void> sendComment(int topicId) async {
    if (!canComment || commentText.trim().isEmpty) return;

    try {
      // 使用当前登录用户ID
      int currentUserId = currentUser!.id;

      // 添加评论
      final newComment = await TopicCommentService.addComment(
        topicId,
        currentUserId,
        commentText.trim(),
      );

      // 清空输入框
      commentText = '';

      // 更新评论列表 - 插入到最前面
      comments.insert(0, newComment);

      // 重新加载话题数据以获取更新的百分比
      final updatedTopic = TopicService.getTopicById(topicId);
      if (updatedTopic != null) {
        topic = updatedTopic;
      }

      // 刷新MessageStore中的话题列表
      await _rootStore.messageStore.loadTopics();
    } catch (e) {
      print('发送评论失败: $e');
    }
  }

  // 登录方法 - 导航到登录页面
  @action
  void navigateToLogin(BuildContext context) {
    // 使用GoRouter导航到登录页面，登录成功后会自动返回并触发 didPopNext
    context.push('/login').then((_) {
      // 此处不需要额外处理，因为 didPopNext 会自动刷新状态
      print('从登录页面返回 TopicPage');
    });
  }

  // 格式化时间戳的辅助方法
  String formatTimestamp(DateTime timestamp) {
    final now = DateTime.now();
    final difference = now.difference(timestamp);

    if (difference.inDays > 365) {
      return '${(difference.inDays / 365).floor()} years ago';
    } else if (difference.inDays > 30) {
      return '${(difference.inDays / 30).floor()} months ago';
    } else if (difference.inDays > 0) {
      return '${difference.inDays} days ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} hours ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} minutes ago';
    } else {
      return 'just now';
    }
  }
}
